<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：幻灯片管理控制器
 * 作者：王楠
 * 创建日期：2017-09-15
 */
class BannerController extends CommonController {

    public function bannerlist() {
	$app_code = $this->app_code;
	$state_enum = getenumbykey('banner_state');
	$state_arr = getarrbyenum($state_enum);
	$type_enum = getenumbykey('banner_type');
	$type_arr = getarrbyenum($type_enum);
	$state = trim(I('ddlstate'));
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	$keyword = trim(I('txtkeyword'));
	$map['app_flag'] = $app_code;
	if (!empty($state)) {
	    $map['state'] = $state;
	}
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	if (!empty($keyword)) {
	    $where['chat_banner.id'] = array('eq', $keyword);
	    $where['chat_banner.name'] = array('like', '%' . $keyword . '%');
	    $where['chat_admin.username'] = array('like', '%' . $keyword . '%');
	    $where['chat_admin.name'] = array('like', '%' . $keyword . '%');
	    $where['_logic'] = 'or';
	    $map['_complex'] = $where;
	}
	$viewModel = new ViewModel\BannerViewModel();
	$total = $viewModel->where($map)->count();
	$row = '5';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$field = array(
	    'id', 'name', 'img', 'link', 'state', 'img_type', 'username', 'admin_name', 'ctime'
	);
	$data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc')->select();
	foreach ($data as $key => $value) {
	    $link = $data[$key]['link'];
	    $link_len = mb_strlen($link, 'utf8');
	    if (!empty($link) && $link_len > 40) {
		$link = mb_substr($link, 0, 19, 'utf8') . '…' . mb_substr($link, $link_len - 20, $link_len, 'utf8');
	    }
	    $data[$key]['link_text'] = $link;
	    $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
	    $data[$key]['type_text'] = $type_enum[$data[$key]['img_type']];
	    $data[$key]['admin_name'] = empty($data[$key]['admin_name']) ? $data[$key]['username'] : $data[$key]['admin_name'];
	    $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
	    $data[$key]['state_lab'] = $data[$key]['state'] == '1' ? '下架' : '上架';
	    $data[$key]['state_class'] = $data[$key]['state'] == '1' ? 'btn-danger' : 'btn-info';
	}
	$search = array('statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'statearr' => $state_arr,
	    'search' => $search
	));
	$this->display();
    }

    public function banneradd() {
	$id = I('id');
	$btnname = '添加';
	$columnname = '添加幻灯片';
	$state_enum = getenumbykey('banner_state');
	$state_arr = getarrbyenum($state_enum);
	$type_enum = getenumbykey('banner_type');
	$type_arr = getarrbyenum($type_enum);
	if (!empty($id)) {
	    $columnname = '修改幻灯片';
	    $btnname = '修改';
	    $viewModel = new ViewModel\BannerViewModel();
	    $data = $viewModel->where(array('id' => $id))->find();
	    $img = $data['img'];
	    $name = $data['name'];
	    $link = $data['link'];
	    $state = $data['state'];
	    $type = $data['img_type'];
	    $admin_name = empty($data['admin_name']) ? $data['username'] : $data['admin_name'];
	    $ctime = date('Y-m-d H:i', $data['ctime']);
	}
	foreach ($state_arr as $key => $value) {
	    if ($state == $value['value']) {
		$state_arr[$key]['selected'] = "selected='selected'";
	    }
	}
	foreach ($type_arr as $key => $value) {
	    if ($type == $value['value']) {
		$type_arr[$key]['selected'] = "selected='selected'";
	    }
	}
	$this->assign(array(
	    'id' => $id,
	    'img' => $img,
	    'name' => $name,
	    'link' => $link,
	    'state' => $state,
	    'type' => $type,
	    'admin_name' => $admin_name,
	    'ctime' => $ctime,
	));
	$this->assign('columnname', $columnname);
	$this->assign('btnname', $btnname);
	$this->assign('statearr', $state_arr);
	$this->assign('typearr', $type_arr);
	$this->display();
    }

    public function banneraddsubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$app_code = $this->app_code;
	$admin_id = $this->admin_id;
	$id = I('id');
	$img = trim(I('img'));
	$name = trim(I('name'));
	$link = trim(I('link'));
	$state = trim(I('state'));
	$type = trim(I('type'));
	if (empty($img)) {
	    $response = array('ret' => '1002', 'code' => '图片不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (empty($name)) {
	    $response = array('ret' => '1002', 'code' => '名称不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
//	if (empty($link)) {
//	    $response = array('ret' => '1002', 'code' => '链接不能为空！');
//	    return $this->ajaxReturn($response, 'json');
//	}
	if (empty($state)) {
	    $state = '1';
	}
	$model = M('chat_banner');
	$data['img'] = $img;
	$data['name'] = $name;
	$data['link'] = $link;
	$data['state'] = $state;
	$data['img_type'] = $type;
	if (empty($id)) {
	    $data['admin_id'] = $admin_id;
	    $data['ctime'] = time();
	    $data['app_flag'] = $app_code;
	}
	if (!empty($id)) {
	    if ($model->where(array('id' => $id))->save($data)) {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    } else {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    }
	} else {
	    if ($model->add($data)) {
		$response = array('ret' => '1001', 'code' => '添加成功！');
	    } else {
		$response = array('ret' => '1002', 'code' => '添加失败！');
	    }
	}
	return $this->ajaxReturn($response, 'json');
    }

    public function flagsubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_banner');
	    $data = $model->where(array('id' => $id))->find();
	    if ($data) {
		$state = $data['state'];
		$lab = $state == '1' ? '下架' : '上架';
		$state = $state == '1' ? '2' : '1';
		$data['state'] = $state;
		$result = $model->save($data);
		if ($result) {
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => $lab . '成功！', 'data' => $state));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => $lab . '失败！', 'data' => $state));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该幻灯片可能已被删除！'));
	    }
	}
    }

    public function deletesubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_banner');
	    $result = $model->where(array('id' => $id))->delete();
	    if ($result) {
		return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！'));
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！'));
	    }
	}
    }

    //上传图片
    public function imgupload() {
	$config = [
	    'maxSize' => 1048576, // 设置附件上传大小
	    'exts' => ['jpg', 'gif', 'png', 'jpeg'], // 设置附件上传类型
	    'rootPath' => './Uploads/banner/', // 设置附件上传根目录
	    'savePath' => '', // 设置附件上传（子）目录
	    'autoSub' => false,
	    'subName' => '',
	    'saveName' => array('uniqid', ''),
	];
	$rootPath = $config['rootPath'];
	if (!is_dir($rootPath)) {
	    mkdir($rootPath);
	}
	$upload = new \Think\Upload($config); // 实例化上传类
	// 上传单个文件
	$info = $upload->upload();
	if (!$info) {// 上传错误提示错误信息
	    $error = $upload->getError();
	    $data['ret'] = '1002';
	    $data['code'] = $error;
	    echo json_encode($data);
	} else {// 上传成功 获取上传文件信息
	    $access_key_id = C('ACCESS_KEY_ID');
	    $access_key_secret = C('ACCESS_KEY_SECRET');
	    $img_url = C('IMG_URL');
	    $img_url2 = C('IMG_URL2');
	    $picName = $info['logoimg']['savename'];
	    $picSize = $info['logoimg']['size'];
	    $picTmp = $info['logoimg']['tmp_name'];
	    $success = new \Vendor\OSS\OssClient($access_key_id, $access_key_secret, $img_url2);
	    $ext = explode('.', $picName)[1];
	    $picRemoteName = 'pc_banner_' . time() . rand(100000, 999999) . '.' . $ext;
	    $bucket = C('BUCKET');
	    $object = 'banner/' . $picRemoteName;
	    $filePath = $rootPath . $picName;
	    try {
		$success->uploadFile($bucket, $object, $filePath);
		unlink($rootPath . $picName);
		$img = $img_url . '/' . $object;
                $data['ret'] = '1001';
                $data['code'] = '上传成功！';
		$data['data'] = $img;
		echo json_encode($data);
	    } catch (OssException $e) {
		$response = array('ret' => '1002', 'code' => '远程上传错误！');
		echo json_encode($data);
	    }
	    
//	    //返回本地路径
//	    $img = C('LOCALHOST_URL') . '/Uploads/banner/' . $info['logoimg']['savename'];
//	    $data['ret'] = '1001';
//	    $data['code'] = '上传成功！';
//	    $data['data'] = $img;
//	    echo json_encode($data);
	}
    }

}
